package top.xin1901.j2ecd.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import top.xin1901.j2ecd.beans.Role;
import top.xin1901.j2ecd.beans.dbo.RoleDbO;
import top.xin1901.j2ecd.dao.RoleDao;
import top.xin1901.j2ecd.service.RoleService;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * @author HeYunjia
 */

@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleDao roleDao;

    @Override
    @Transactional
    public Role insertOne(Role role) {
        Date date = new Date();
        role.setGmtCreate(date);
        role.setGmtModified(date);

        RoleDbO roleDbO = role.toRoleDbO();
        int insertRole = roleDao.insert(roleDbO);
        if (insertRole != 1) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return null;
        }

        List<Long> permissions = role.toPermissionIds();
        int insertPermissions = roleDao.insertPermissions(roleDbO.getRoleId(), permissions);
        if (insertPermissions != permissions.size()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return null;
        }

        return roleDao.selectOne(roleDbO.getRoleId());
    }

    @Override
    public List<Role> selectAll() {
        return roleDao.selectAll();
    }

    @Override
    public Role selectOne(Long RoleId) {
        return roleDao.selectOne(RoleId);
    }
}
